// Token管理工具
export interface TokenInfo {
  accessToken: string;
  refreshToken: string;
  expiresIn: number;
  tokenType: string;
}

// Token存储键名
const ACCESS_TOKEN_KEY = 'access_token';
const REFRESH_TOKEN_KEY = 'refresh_token';
const TOKEN_EXPIRES_KEY = 'token_expires';
const USER_INFO_KEY = 'userInfo';

// 获取访问token
export const getAccessToken = (): string | null => {
  return localStorage.getItem(ACCESS_TOKEN_KEY);
};

// 获取刷新token
export const getRefreshToken = (): string | null => {
  return localStorage.getItem(REFRESH_TOKEN_KEY);
};

// 获取token过期时间
export const getTokenExpires = (): number | null => {
  const expires = localStorage.getItem(TOKEN_EXPIRES_KEY);
  return expires ? parseInt(expires) : null;
};

// 设置token信息
export const setTokenInfo = (tokenInfo: TokenInfo): void => {
  const expiresTime = Date.now() + tokenInfo.expiresIn * 1000;
  
  localStorage.setItem(ACCESS_TOKEN_KEY, tokenInfo.accessToken);
  localStorage.setItem(REFRESH_TOKEN_KEY, tokenInfo.refreshToken);
  localStorage.setItem(TOKEN_EXPIRES_KEY, expiresTime.toString());
};

// 更新访问token
export const updateAccessToken = (accessToken: string, expiresIn: number): void => {
  const expiresTime = Date.now() + expiresIn * 1000;
  
  localStorage.setItem(ACCESS_TOKEN_KEY, accessToken);
  localStorage.setItem(TOKEN_EXPIRES_KEY, expiresTime.toString());
};

// 清除所有token
export const clearTokens = (): void => {
  localStorage.removeItem(ACCESS_TOKEN_KEY);
  localStorage.removeItem(REFRESH_TOKEN_KEY);
  localStorage.removeItem(TOKEN_EXPIRES_KEY);
  localStorage.removeItem(USER_INFO_KEY);
};

// 检查token是否过期
export const isTokenExpired = (): boolean => {
  const expires = getTokenExpires();
  if (!expires) return true;
  
  // 提前5分钟刷新token
  return Date.now() >= expires - 5 * 60 * 1000;
};

// 检查是否有有效的token
export const hasValidToken = (): boolean => {
  const accessToken = getAccessToken();
  return !!accessToken && !isTokenExpired();
};

// 获取用户信息
export const getUserInfo = (): any => {
  const userInfo = localStorage.getItem(USER_INFO_KEY);
  return userInfo ? JSON.parse(userInfo) : null;
};

// 设置用户信息
export const setUserInfo = (userInfo: any): void => {
  localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo));
}; 